package io.github.bt2043.h2;

import org.h2.tools.Server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by henyue on 2017-3-16.
 */
public class TestH2 {
    public static void main(String[] args) {
        Server h2server = null;
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("org.h2.Driver");
            h2server = Server.createTcpServer().start();
            conn = DriverManager.getConnection(
                    "jdbc:h2:tcp://localhost/mem:test",
                    "sa",
                    "");
            stmt = conn.createStatement();
            stmt.executeUpdate("create table test_mem(id int primary key, name varchar(255));");
            stmt.executeUpdate("insert into test_mem values(1, 'Kong');");
            stmt.executeUpdate("insert into test_mem values(2, 'Smile');");
            ResultSet rs = stmt.executeQuery("select * from test_mem");
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " : " + rs.getString("name"));
            }
            rs.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (h2server != null) {
                h2server.stop();
            }
        }
    }
}
